using System;
using System.Data;
using System.Configuration;
using System.Collections.Generic;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using BusinessLayer;
using BusinessLayer.Model;

public partial class Search : System.Web.UI.Page
{
    public ISearchService searchService;

    public ISearchService SearchService
    {
        get { return searchService; }
        set { searchService = value; }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        string searchPhrase = Request.QueryString["s"];

        if( searchPhrase != null && !searchPhrase.Equals(string.Empty)){
            this.PanelSearch.Visible = false;
            search(searchPhrase);
        }
    }

    public void search(string phrase)
    {
        IList<SearchResult> result = SearchService.FindPhrase(phrase);
        markPhrase(ref result, phrase);
        this.resultRpt.DataSource = result;
        this.resultRpt.DataBind();
    }
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        string s = HttpUtility.HtmlEncode(this.tbPhrase.Text);
        Response.Redirect("~/Search.aspx?s=" + s);
    }

    private void markPhrase(ref IList<SearchResult> result, string phrase)
    {
        foreach (SearchResult sr in result)
        {
            int startIndex = 0;
            int endIndex = 0;
            int indexOfLastToken = 0;
            int indexOfFirstToken = sr.Content.Length;

            char [] delims = " \t\n\r".ToCharArray();
            string [] tokens = phrase.Split(delims);

            foreach (string token in tokens)
            {
                int temp = sr.Content.IndexOf(token);

                if ( temp > indexOfLastToken)
                {
                    indexOfLastToken = temp;
                }

                if (temp < indexOfFirstToken)
                {
                    indexOfFirstToken = temp;
                }

                if (token.Length == 0) continue;
                else
                {
                   sr.Content = sr.Content.Replace(phrase, "<b style='color:green'>" + token + "</b>");

                }

            }

            if (indexOfLastToken + 500 > sr.Content.Length)
            {
                endIndex = sr.Content.Length - 1;
            }
            else
            {
                endIndex = indexOfLastToken + 500;
            }

            if (indexOfFirstToken - 500 < 0)
            {
                startIndex = 0;

            } else {

                startIndex = indexOfFirstToken - 500;
            }
            if(sr.Content.Length > 1000)
                sr.Content = sr.Content.Substring(startIndex, endIndex - startIndex) + "...";
        }

    }
}
